<template>
  <view class="page-wrapper">
    <view class="item">
      <view class="item-title">车牌号码<view class="item-status">{{getStatus}}</view>
      </view>
      <view class="car-number">
        <view class="number" v-for="(item,index) in carNumber">
          <view :class="index=== carNumber.length-1&&carNumber.length===9?'energy':''">{{item}}</view>
        </view>
        <view v-if="carNumber.length===8" class="new-energy">
          <view>+</view>
          <view class="new-energy-text">新能源</view>
        </view>
      </view>
      <view class="line"><u-line></u-line></view>
      <view class="car-item">
        <view class="car-title">司机姓名</view>
        <view class="car-content">
          <u--input placeholder="请输入司机姓名" border="bottom" v-model="carInfo.driverName" :readonly="true"></u--input>
        </view>
      </view>
      <view class="car-item">
        <view class="car-title">品牌车型</view>
        <view class="car-content" @click="selectBrand">
          <u--input placeholder="请选择品牌车型" border="bottom" v-model="carInfo.brandModel" :readonly="true"></u--input>
          <view class="car-icon"><u-icon name="arrow-right"></u-icon></view>
        </view>
      </view>
      <view class="car-item">
        <view class="car-title">车辆类型</view>
        <view class="car-content" @click="showCarType = true">
          <u--input placeholder="请选择车辆类型" border="bottom" v-model="carInfo.carType" :readonly="true"></u--input>
          <view class="car-icon"><u-icon name="arrow-right"></u-icon></view>
        </view>
      </view>
      <view class="car-item">
        <view class="car-title">车辆长度</view>
        <view class="car-content" @click="showCarLength = true">
          <u--input placeholder="请如实填写车长" border="bottom" v-model="carInfo.carLength" :readonly="true"></u--input>
          <view class="car-icon"><u-icon name="arrow-right"></u-icon></view>
        </view>
      </view>
      <view class="car-item">
        <view class="car-title">车辆载重</view>
        <view class="car-content">
          <u--input placeholder="请填写总质量" v-model="carInfo.carLoad" border="none" type="digit"
            @input="formatDecimal(carInfo.carLoad,3)"></u--input>
          <view class="car-icon">吨</view>
        </view>
      </view>
    </view>
    <view class="item">
      <view class="item-title">车头照片</view>
      <view class="upload">
        <uploadImg :width="150" :height="170" uploadText="添加图片" @handleImg="handleImg" @deleteImg="deleteImg"
          :previewUrl="previewUrl" />
      </view>
    </view>
    <view class="action-wrapper">
      <button class="next-step" @click="saveCar">保存</button>
    </view>
    <u-picker :show="showCarType" :columns="carTypeList" keyName="motorcycle" title="选择车型" @close="showCarType=false"
      @cancel="showCarType=false" @confirm="selectCarType" closeOnClickOverlay></u-picker>
    <u-picker :show="showCarLength" :columns="carLengthList" keyName="conductor" title="选择长度"
      @close="showCarLength=false" @cancel="showCarLength=false" @confirm="selectCarLength"
      closeOnClickOverlay></u-picker>
    <u-modal :show="showSaveRes" title="提示" content='车辆信息修改成功' confirmColor="#CF1A1B" @confirm="confirmModal"></u-modal>
  </view>
</template>

<script>
  import {
    mapGetters,
    mapActions
  } from 'vuex'
  import uploadImg from '@/components/uploadImg.vue'
  export default {
    components: {
      uploadImg
    },
    data() {
      return {
        carNumber: [],
        carInfo: {},
        carTypeList: [],
        showCarType: false,
        carLengthList: [],
        showCarLength: false,
        showSaveRes: false,
        previewUrl: [], //预览图地址
        financeScale: ''
      };
    },
    computed: {
      ...mapGetters('user', ['getUserInfo']),
      getStatus() {
        if (this.carInfo.state === 1) {
          return '已认证'
        } else {
          return '未认证'
        }
      },
      formatDecimal() { //str当前输入值，num是想要保留的小数位数
        return function(str, num) {
          str = String(str)
          if (!str.trim()) {
            return str
          }
          let len1 = str.substr(0, 1)
          let len2 = str.substr(1, 1)
          // 如果第一位是0，第二位不是点，就用数字把点替换掉
          if (str.length > 1 && len1 == 0 && len2 !== '.') {
            str = str.substr(1,1)
          }
          // 第一位不能是.
          if (len1 === '.') {
            str = ''
          }
          // 限制只能输入一个小数点
          if (str.indexOf('.') !== -1) {
            let str_ = str.substr(str.indexOf('.') + 1)
            if (str_.indexOf('.') !== -1) {
              str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
            }
          }
          // 正则替换
          str = str.replace(/[^\d^.]+/g, '') // 保留数字和小数点
          if (num || num === 0) {
            let rest = str.split('.')[1]
            if (rest && rest.length > num) {
              rest = rest.substr(0, num)
              str = str.split('.')[0] + '.' + rest
            }
          }
          this.$nextTick(()=>{
            this.carInfo.carLoad = str
          })
        }
      }
    },
    methods: {
      ...mapActions('user', ['getUserInfoFn']),
      //获取我的车辆信息
      async getCarInfo() {
        uni.showLoading({
          title: '加载中...'
        })
        try {
          let res = await this.$request({
            method: 'GET',
            url: '/terminal-serve-center/merchant-car/getCarInfo',
            data: {
              userId: this.getUserInfo.id
            }
          })
          if (res && res.datas) {
            this.carInfo = {
              ...res.datas
            }
            let {
              plateNum,
              carPic
            } = res.datas
            if (carPic && carPic.length > 0) {
              this.previewUrl.push(carPic)
            }
            if (plateNum && plateNum.length > 0) {
              let numbers = plateNum.split('')
              numbers.splice(2, 0, '.')
              this.carNumber = numbers
            } else {
              this.carNumber = ['X', 'X', '.', 'X', 'X', 'X', 'X', 'X', 'X']
            }
          }
        } catch (e) {
          uni.hideLoading()
          this.carNumber = ['X', 'X', '.', 'X', 'X', 'X', 'X', 'X', 'X']
          console.log('getCarInfo..', e)
        } finally {
          uni.hideLoading()
        }
      },
      //获取车辆类型列表、车辆高度列表
      async getActionList() {
        try {
          let res = await this.$request({
            method: 'POST',
            url: '/terminal-serve-center/ownerController/new/getCarConductorAndMotorcycle',
          })
          if (res && res.datas) {
            let {
              motorcycle,
              conductor
            } = res.datas
            if (motorcycle.length > 0) {
              this.carTypeList = [motorcycle]
            }
            if (conductor.length > 0) {
              this.carLengthList = [conductor]
            }
          }
        } catch (e) {
          console.error(e)
        }
      },
      //选择品牌
      selectBrand() {
        uni.setStorageSync('authSource', 'myCar')
        uni.navigateTo({
          url: `/indexPack/car/brand`,
          events: {
            //获取下级页面传递回来的参数
            setBrandData: data => {
              this.carInfo.brandModel = data.seriesName
              this.carInfo.levelId = data.levelId
            }
          }
        })
      },
      //选择车辆类型
      selectCarType(e) {
        this.carInfo.carType = e.value[0].motorcycle
        this.showCarType = false
      },
      //选择车辆长度
      selectCarLength(e) {
        this.carInfo.carLength = e.value[0].conductor
        this.showCarLength = false
      },
      //获取上传后的图片
      handleImg(url) {
        //删除图片
        if (url) {
          this.carInfo.carPic = url
        } else {
          this.carInfo.carPic = ''
        }
      },
      //删除图片后处理接口传参
      deleteImg(index) {
        if (index === 0) {
          this.carInfo.carPic = ''
        }
      },
      //保存车辆信息
      saveCar() {
        this.$request({
          method: 'POST',
          url: '/terminal-serve-center/merchant-car/edit',
          data: {
            plateNum: this.carInfo.plateNum,
            carLength: this.carInfo.carLength,
            carLoad: this.carInfo.carLoad,
            carTemplateId: this.carInfo.carTemplateId,
            carPic: this.carInfo.carPic,
            driverName: this.carInfo.driverName,
            carType: this.carInfo.carType,
            levelId: this.carInfo.levelId //品牌车型ID
          }
        }).then((res) => {
          if (res && res.respCode === 200) {
            this.showSaveRes = true
            this.getUserInfoFn()
            uni.$emit('refreshIndex')
          }
        }).catch((e) => {
          console.log('保存车辆信息失败', e)
        })
      },
      confirmModal() {
        this.showSaveRes = false
        uni.navigateBack()
      },
    },

    onLoad() {
      this.getCarInfo()
      this.getActionList()
    }
  }
</script>

<style lang="scss" scoped>
  .page-wrapper {
    .item {
      margin-bottom: 20rpx;
      background-color: #FFFFFF;
      padding-bottom: 28rpx;

      .item-title {
        display: flex;
        font-size: 28rpx;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
        margin-left: 32rpx;
        padding-top: 32rpx;
        margin-bottom: 36rpx;
      }

      .item-status {
        margin-left: 16rpx;
        width: 92rpx;
        border-radius: 6rpx;
        border: 2rpx solid #E48900;
        font-weight: 400;
        font-size: 24rpx;
        color: #E48900;
        text-align: center;
      }

      .car-number {
        display: flex;
        margin: 0 32rpx;

        .number {
          flex: 0.5;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #F9F9F9;
          border-radius: 6rpx;
          border: 2rpx solid #EFEFEF;
          margin: 0 4rpx;
          font-size: 28rpx;
          height: 78rpx;

          .energy {
            font-size: 28rpx;
            background-color: #DFFFE1;
            border-color: #CFECD1;
            font-weight: 400;
            color: #49AC4F;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          &:first-child {
            flex: 0.8;
            margin-left: 0;
          }

          &:nth-child(3) {
            background-color: #FFFFFF;
            border: none;
            font-weight: 800;
            color: rgba(0, 0, 0, 0.65);
            margin: 0;
            flex: 0.1;
          }

          &:last-child {
            margin-right: 0;
          }
        }

        .new-energy {
          flex: 0.8;
          height: 78rpx;
          text-align: center;
          background-color: #DFFFE1;
          color: #49AC4F;
          border-radius: 6rpx;
          border: 2rpx solid #EFEFEF;

          &-text {
            font-size: 24rpx;
          }
        }
      }

      .line {
        margin: 14rpx 32rpx 30rpx 32rpx;
      }

      .car-item {
        display: flex;
        margin: 0 48rpx 0 32rpx;
        height: 86rpx;
        align-items: center;


        .car-title {
          width: 112rpx;
          height: 28rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.65);
        }

        .car-content {
          flex: 1;
          margin-left: 72rpx;
          position: relative;


          .car-icon {
            position: absolute;
            width: 14rpx;
            right: 0;
            bottom: 16rpx;
          }

        }

        &:last-child .car-content {
          padding-left: 9px;
        }

        &:last-child .car-content .car-icon {
          position: absolute;
          width: 14rpx;
          right: 20rpx;
          bottom: 0rpx;
        }
      }

      .upload {
        margin-left: 32rpx;
        margin-top: 56rpx;

        /deep/ .u-upload__button {
          margin: 0;
        }

        /deep/ .u-upload__button .u-icon__icon {
          font-size: 40px !important;
        }

        /deep/ .u-upload__button__text {
          font-size: 12px;
          margin-top: 26rpx;
        }
      }
    }

    .action-wrapper {
      position: fixed;
      width: 100%;
      bottom: 0;
      height: 178rpx;
      background: #FFFFFF;

      .next-step {
        height: 80rpx;
        line-height: 80rpx;
        background: #CF1A1B;
        border-radius: 8rpx;
        margin: 32rpx;
        color: #FFFFFF;
        font-size: 28rpx;
        font-weight: 400;
      }
    }

    /deep/ .u-action-sheet {
      min-height: 200rpx;
      max-height: 500rpx;
      overflow: auto;
    }

    /deep/ .u-modal__content {
      text-align: center;
    }
  }
</style>